package com.fanyouzhao.ehome.web.servlet; /**
 * @Author: fanyouzhao
 * @Date: 14:45 2021/5/8
 */

import com.alibaba.fastjson.JSON;
import com.fanyouzhao.ehome.entity.Admin;
import com.fanyouzhao.ehome.service.AdminService;
import com.fanyouzhao.ehome.service.impl.AdminServiceImpl;
import com.fanyouzhao.ehome.util.JsonResult;
import com.fanyouzhao.ehome.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "AdminServlet", value = "/admin")
public class AdminServlet extends HttpServlet {

    private final AdminService adminService = new AdminServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //中文处理
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        ((HttpServletResponse) response).setHeader("content-Type", "text/html;charset=UTF-8");

        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(null);

        String method = request.getHeader("method");
        switch (method) {
            case "login": {
                String phone = request.getParameter("phone");
                String pwd = request.getParameter("pwd");
                try {
                    Admin login = login(phone, pwd);
                    if (login != null) {
                        HttpSession session = request.getSession();
                        session.setAttribute("phone", phone);
                        jsonResult = new JsonResult("1", "登录成功", login);
                    } else {
                        jsonResult = new JsonResult("0", "登录失败，用户名或密码错误！");
                        System.out.println("jsonResult = " + jsonResult);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "exit": {
//                String phone = request.getParameter("phone");
                HttpSession session = request.getSession();
                session.removeAttribute("phone");
                jsonResult = new JsonResult("1", "退出成功");
                break;
            }
            default:
                break;
        }
        ResponseUtil.send(response, JSON.toJSONString(jsonResult.getValues()));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public Admin login(String phone, String pwd) throws Exception {
        return adminService.login(phone, pwd);
    }
}
